//
//  MomentSectionCell+ConfigureForMomentItem.m
//  WeChatMoments
//
//  Created by Jiang on 2019/8/27.
//  Copyright © 2019 SilverFruity. All rights reserved.
//

#import "MomentSectionCell+ConfigureForMomentItem.h"
#import <YYText/YYText.h>

@implementation MomentSectionCell (ConfigureForMomentItem)
- (void)configureForMomentItem:(MomentItem *)item{
    [self.avatarImageView sp_setImageWithURL:item.sender.avatar];
    
    if (!item.content) {
        self.contentLabel.text = nil;
        return;
    }
    // http[s]?:// ***
    [self.usernameButton setTitle:item.sender.username forState:UIControlStateNormal];
    NSString *string = item.content;
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:item.content attributes:@{NSFontAttributeName:self.contentLabel.font}];
    NSString *reg = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:reg
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
    if (arrayOfAllMatches.count == 0) {
        self.contentLabel.text = item.content;
    }else{
        for (NSTextCheckingResult *match in arrayOfAllMatches){
            [attributeString yy_setAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:match.range];
        }
        self.contentLabel.attributedText = attributeString;
    }
}
@end
